import React, { useState, forwardRef } from 'react';
import { 
  Box, 
  Typography, 
  Grid, 
  CircularProgress, 
  Card, 
  CardContent,
  Divider,
  Alert,
  Button,
  Chip,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Slide
} from '@mui/material';
import KeyboardArrowLeftIcon from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import CloseIcon from '@mui/icons-material/Close';
import { useAuth } from 'contexts/AuthContext';
import { useQuery } from 'react-query';
import { CustomerInvoices, Plans } from 'api/queries';
import { useTranslation } from 'react-i18next';
import { PaymentButton } from 'components/atoms/ReusableButton';
import { formatMoney } from 'libs/utils';
import moment from 'moment';

/**
 * PaymentHistoryUserInterface - Unified component for payment history and invoice details
 * 
 * This component can:
 * 1. Display payment history
 * 2. Display invoice details
 * 3. Pay invoices via hosted URL
 * 
 * @param {Object} props
 * @param {string} props.invoiceId - Optional invoice ID for specific invoice details
 * @param {string} props.actionType - Optional action type: 'view', 'details'
 * @param {string} props.title - Optional custom title
 * @param {string} props.description - Optional custom description
 * @param {boolean} props.initiallyExpanded - Whether to show the UI initially or just the button
 * @param {string} props.buttonText - Optional custom button text to override translation
 * @param {boolean} props.simpleButton - If true, renders just the button without any wrappers
 * 
 * @example
 * // Basic usage - shows button that reveals payment history
 * <PaymentHistoryUserInterface />
 * 
 * @example
 * // Invoice details interface
 * <PaymentHistoryUserInterface 
 *   invoiceId="in_123456"
 *   actionType="details"
 *   initiallyExpanded={false}
 * />
 * 
 * @example
 * // Simple button with custom text
 * <PaymentHistoryUserInterface
 *   buttonText="View Your Invoice History"
 *   simpleButton={true}
 * />
 */
const PaymentHistoryUserInterface = ({ 
  invoiceId,
  actionType = 'view',
  title,
  description,
  initiallyExpanded = false,
  buttonText,
  simpleButton = false
}) => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const [dialogOpen, setDialogOpen] = useState(initiallyExpanded);
  const [actionState, setActionState] = useState(null);
  const [invoices, setInvoices] = useState([]);
  const [activeInvoiceIndex, setActiveInvoiceIndex] = useState(0);
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [selectedInvoiceId, setSelectedInvoiceId] = useState(null);
  
  // Transition component for Dialog
  const DialogTransition = forwardRef(function Transition(props, ref) {
    return <Slide direction="up" ref={ref} {...props} />;
  });

  // Queries
  const invoicesQuery = useQuery(
    ["CustomerInvoices", user?.accountId],
    CustomerInvoices,
    { 
      retry: false,
      enabled: !!user?.accountId && dialogOpen,
      onSuccess: (data) => {
        const allInvoices = data?.data || [];
        setInvoices(allInvoices);
        
        // Find selected invoice if invoiceId provided
        if (invoiceId) {
          const index = allInvoices.findIndex(inv => inv.id === invoiceId);
          if (index !== -1) {
            setActiveInvoiceIndex(index);
            
            if (actionType === 'details') {
              setSelectedInvoiceId(invoiceId);
              setDetailsDialogOpen(true);
            }
          }
        }
      }
    }
  );

  const plansQuery = useQuery("Plans", Plans, {
    retry: false,
    enabled: dialogOpen
  });

  // Format date from Unix timestamp
  const formatDate = (unixTimestamp) => {
    if (!unixTimestamp) return '';
    return moment.unix(unixTimestamp).format("DD/MM/YYYY");
  };

  // Get currency
  const getCurrency = () => {
    if (plansQuery.data?.data?.plans?.length > 0) {
      return plansQuery.data.data.plans[0].currency || 'USD';
    }
    return 'USD';
  };

  // Handler for action state changes
  const handleActionStateChange = (state) => {
    setActionState(state);
    
    // Close dialog on success
    if (state.success && detailsDialogOpen) {
      setDetailsDialogOpen(false);
    }
    
    // Automatically reset state after 3 seconds
    setTimeout(() => {
      setActionState(null);
    }, 3000);
  };

  // Open main dialog
  const openDialog = () => {
    setDialogOpen(true);
    return { 
      message: actionType === 'details' 
        ? t("common.loadingInvoiceDetails") 
        : t("common.loadingPaymentHistory") 
    };
  };

  // Close main dialog
  const closeDialog = () => {
    setDialogOpen(false);
    setActionState(null);
  };
  
  // Open invoice details dialog
  const openDetailsDialog = (id) => {
    setSelectedInvoiceId(id);
    setDetailsDialogOpen(true);
  };
  
  // Close invoice details dialog
  const closeDetailsDialog = () => {
    setDetailsDialogOpen(false);
  };
  
  // Navigate to next invoice
  const nextInvoice = () => {
    setActiveInvoiceIndex((prevIndex) => {
      return (prevIndex + 1) % invoices.length;
    });
  };
  
  // Navigate to previous invoice
  const prevInvoice = () => {
    setActiveInvoiceIndex((prevIndex) => {
      return prevIndex === 0 ? invoices.length - 1 : prevIndex - 1;
    });
  };
  
  // Get currently active/selected invoice
  const getSelectedInvoice = (id) => {
    return invoices.find(invoice => invoice.id === id);
  };
  
  // Get current active invoice
  // eslint-disable-next-line
  const getCurrentInvoice = () => {
    if (!invoices.length || activeInvoiceIndex >= invoices.length) return null;
    return invoices[activeInvoiceIndex];
  };

  // Loading state
  const isLoading = invoicesQuery.isLoading || plansQuery.isLoading;
  const hasError = invoicesQuery.isError || plansQuery.isError;

  // If not expanded, just show the button
  if (!dialogOpen) {
    const buttonProps = {
      view: {
        title: title || t("paymentHistory.pageTitle"),
        description: description || t("paymentHistory.pageDescription"),
        buttonText: buttonText || t("paymentHistory.viewPaymentHistory")
      },
      details: {
        title: title || t("paymentHistory.invoiceDetails"),
        description: description || t("paymentHistory.invoiceDetailsDescription"),
        buttonText: buttonText || t("paymentHistory.viewInvoiceDetails")
      }
    };

    const currentProps = buttonProps[actionType] || buttonProps.view;
    
    // If simpleButton is true, render just the button without wrappers
    if (simpleButton) {
      return (
        <Button
          variant="contained"
          color="primary"
          size="large"
          onClick={openDialog}
        >
          {currentProps.buttonText}
        </Button>
      );
    }

    return (
      <Box textAlign="center" py={4}>
        <Typography variant="h5" component="h2" gutterBottom>
          {currentProps.title}
        </Typography>
        
        {currentProps.description && (
          <Typography paragraph>
            {currentProps.description}
          </Typography>
        )}
        
        <Box mt={3}>
          <Button
            variant="contained"
            color="primary"
            size="large"
            onClick={openDialog}
          >
            {currentProps.buttonText}
          </Button>
        </Box>
      </Box>
    );
  }

  // Render invoice details dialog
  const renderInvoiceDetailsDialog = () => {
    if (!selectedInvoiceId) return null;
    
    const selectedInvoice = getSelectedInvoice(selectedInvoiceId);
    if (!selectedInvoice) return null;
    
    const currency = getCurrency();
    
    return (
      <Dialog 
        open={detailsDialogOpen} 
        onClose={closeDetailsDialog}
        fullWidth
        maxWidth="md"
      >
        <DialogTitle>
          {t("paymentHistory.invoiceDetails")} - {selectedInvoice.number}
          <IconButton
            aria-label="close"
            onClick={closeDetailsDialog}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <Box mb={3}>
            <Grid container spacing={2}>
              <Grid item xs={12} md={6}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      {t("paymentHistory.invoiceDetails")}
                    </Typography>
                    
                    <TableContainer>
                      <Table size="small">
                        <TableBody>
                          <TableRow>
                            <TableCell component="th" scope="row">
                              {t("paymentHistory.date")}
                            </TableCell>
                            <TableCell>
                              {formatDate(selectedInvoice.created)}
                            </TableCell>
                          </TableRow>
                          <TableRow>
                            <TableCell component="th" scope="row">
                              {t("paymentHistory.amount")}
                            </TableCell>
                            <TableCell>
                              {formatMoney("it", currency, selectedInvoice.total / 100)}
                            </TableCell>
                          </TableRow>
                          <TableRow>
                            <TableCell component="th" scope="row">
                              {t("paymentHistory.status")}
                            </TableCell>
                            <TableCell>
                              {selectedInvoice.paid ? 
                                t("paymentHistory.paid") : 
                                t("paymentHistory.pending")}
                            </TableCell>
                          </TableRow>
                          <TableRow>
                            <TableCell component="th" scope="row">
                              {t("paymentHistory.invoiceId")}
                            </TableCell>
                            <TableCell sx={{ wordBreak: 'break-all' }}>
                              {selectedInvoice.id}
                            </TableCell>
                          </TableRow>
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </CardContent>
                </Card>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      {t("paymentHistory.actions")}
                    </Typography>
                    
                    <Grid container spacing={2}>
                      {selectedInvoice.hosted_invoice_url && selectedInvoice.status === "open" && (
                        <Grid item xs={12}>
                          <PaymentButton 
                            actionType="pay"
                            invoiceId={selectedInvoice.id}
                            hostedUrl={selectedInvoice.hosted_invoice_url}
                            isPaid={selectedInvoice.paid}
                            variant="contained"
                            fullWidth
                            onStateChange={handleActionStateChange}
                          />
                        </Grid>
                      )}
                    </Grid>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>
            
            {actionState && actionState.error && (
              <Alert severity="error" sx={{ mt: 2 }}>
                {actionState.error.message || t("common.actionFailed")}
              </Alert>
            )}
            
            {actionState && actionState.success && (
              <Alert severity="success" sx={{ mt: 2 }}>
                {actionState.result?.message || t("common.actionSuccessful")}
              </Alert>
            )}
          </Box>
          
          {selectedInvoice.lines && selectedInvoice.lines.data && selectedInvoice.lines.data.length > 0 && (
            <Box>
              <Typography variant="h6" gutterBottom>
                {t("paymentHistory.invoiceItems")}
              </Typography>
              
              <TableContainer component={Paper} variant="outlined">
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>{t("paymentHistory.description")}</TableCell>
                      <TableCell>{t("paymentHistory.period")}</TableCell>
                      <TableCell align="right">{t("paymentHistory.amount")}</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {selectedInvoice.lines.data.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>{item.description}</TableCell>
                        <TableCell>
                          {item.period ? `${formatDate(item.period.start)} - ${formatDate(item.period.end)}` : '-'}
                        </TableCell>
                        <TableCell align="right">
                          {formatMoney("it", currency, item.amount / 100)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={closeDetailsDialog}>
            {t("common.close")}
          </Button>
        </DialogActions>
      </Dialog>
    );
  };
  
  // Render invoice cards with CSS-based sliding transitions
  const renderInvoiceContent = () => {
    if (!invoices.length) return null;
    
    const currency = getCurrency();
    
    return (
      <Box sx={{ 
        position: 'relative', 
        overflow: 'hidden', 
        height: '200px',  // Fixed height to prevent jumping
        mb: 2
      }}>
        {invoices.map((invoice, index) => (
          <Box
            key={invoice.id}
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              transition: 'transform 300ms ease, opacity 300ms ease',
              transform: `translateX(${(index - activeInvoiceIndex) * 100}%)`,
              opacity: index === activeInvoiceIndex ? 1 : 0,
              visibility: Math.abs(index - activeInvoiceIndex) <= 1 ? 'visible' : 'hidden', // Only render nearby invoices
              zIndex: index === activeInvoiceIndex ? 2 : 1,
            }}
          >
            <Card variant="outlined">
              <CardContent>
                <Typography variant="h6">
                  {t("paymentHistory.invoice")} {invoice.number}
                </Typography>
                
                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                  {formatDate(invoice.created)}
                </Typography>
                
                <Box display="flex" justifyContent="space-between" alignItems="center" mt={1}>
                  <Typography variant="body2">
                    {t("paymentHistory.amount")}
                  </Typography>
                  <Typography variant="body1" fontWeight="medium">
                    {formatMoney("it", currency, invoice.total / 100)}
                  </Typography>
                </Box>
                
                <Box display="flex" justifyContent="space-between" alignItems="center" mt={1}>
                  <Typography variant="body2">
                    {t("paymentHistory.status")}
                  </Typography>
                  <Chip 
                    label={invoice.paid ? t("paymentHistory.paid") : t("paymentHistory.pending")}
                    color={invoice.paid ? "success" : "warning"}
                    size="small"
                  />
                </Box>
                
                <Divider sx={{ my: 2 }} />
                
                <Button
                  variant="outlined"
                  fullWidth
                  onClick={() => openDetailsDialog(invoice.id)}
                >
                  {t("paymentHistory.viewDetails")}
                </Button>
              </CardContent>
            </Card>
          </Box>
        ))}
      </Box>
    );
  };

  // Main dialog content
  const renderMainDialog = () => {
    // Render loading state
    if (isLoading) {
      return (
        <Box display="flex" justifyContent="center" alignItems="center" p={4}>
          <CircularProgress />
        </Box>
      );
    }
    
    // Render error state
    if (hasError) {
      return (
        <Alert severity="error" sx={{ m: 2 }}>
          {t("common.errorLoadingData")}
        </Alert>
      );
    }
    
    // No invoices found
    if (invoices.length === 0) {
      return (
        <Box textAlign="center" p={3}>
          <Typography variant="h6" gutterBottom>
            {t("paymentHistory.noInvoices")}
          </Typography>
          <Typography variant="body2" paragraph>
            {t("paymentHistory.noInvoicesDescription")}
          </Typography>
          <Button 
            variant="outlined" 
            onClick={() => window.location.href = '/subscription'}
          >
            {t("subscription.viewSubscription")}
          </Button>
        </Box>
      );
    }
    
    // Has invoices
    return (
      <>
        {/* Navigation controls */}
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', mb: 2 }}>
          {invoices.length > 1 && (
            <IconButton onClick={prevInvoice} size="small" aria-label="Previous invoice">
              <KeyboardArrowLeftIcon />
            </IconButton>
          )}
          
          <Typography variant="body2" sx={{ mx: 2 }}>
            {t("paymentHistory.invoiceCount", { current: activeInvoiceIndex + 1, total: invoices.length })}
          </Typography>
          
          {invoices.length > 1 && (
            <IconButton onClick={nextInvoice} size="small" aria-label="Next invoice">
              <KeyboardArrowRightIcon />
            </IconButton>
          )}
        </Box>
        
        {actionState && actionState.success && (
          <Alert severity="success" sx={{ mb: 2 }}>
            {actionState.result?.message || t("common.actionSuccessful")}
          </Alert>
        )}
        
        {actionState && actionState.error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {actionState.error.message || t("common.actionFailed")}
          </Alert>
        )}
        
        {/* Sliding invoice cards */}
        {renderInvoiceContent()}
        
        {/* Help text */}
        <Box sx={{ mt: 3 }}>
          <Typography variant="subtitle2" gutterBottom>
            {t("paymentHistory.needHelp")}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {t("paymentHistory.contactSupport")}
          </Typography>
        </Box>
      </>
    );
  };

  return (
    <>
      {/* Initial button to open dialog */}
      {!dialogOpen && (
        // This section is only rendered if simpleButton is false (handled above)
        <Box textAlign="center" py={4}>
          <Typography variant="h5" component="h2" gutterBottom>
            {title || (actionType === 'details' 
              ? t("paymentHistory.invoiceDetails") 
              : t("paymentHistory.pageTitle"))}
          </Typography>
          
          {description && (
            <Typography paragraph>
              {description}
            </Typography>
          )}
          
          <Box mt={3}>
            <Button
              variant="contained"
              color="primary"
              size="large"
              onClick={openDialog}
            >
              {buttonText || (actionType === 'details' 
                ? t("paymentHistory.viewInvoiceDetails") 
                : t("paymentHistory.viewPaymentHistory"))}
            </Button>
          </Box>
        </Box>
      )}
      
      {/* Main Dialog with Payment History */}
      <Dialog
        open={dialogOpen}
        onClose={closeDialog}
        fullWidth
        maxWidth="sm"
        TransitionComponent={DialogTransition}
      >
        <DialogTitle>
          {title || t("paymentHistory.pageTitle")}
          <IconButton
            aria-label="close"
            onClick={closeDialog}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          {renderMainDialog()}
        </DialogContent>
        <DialogActions>
          <Button onClick={closeDialog}>
            {t("common.close")}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Invoice Details Dialog */}
      {renderInvoiceDetailsDialog()}
    </>
  );
};

export default PaymentHistoryUserInterface;